package com.zhoukai.business.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

public class HttpServletWrite {

    private static final Logger log = LoggerFactory.getLogger(HttpServletWrite.class);

    public static void writeText(HttpServletResponse response, String text) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/plain; charset=utf-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.print(text);
        } catch (IOException var7) {
            log.error("write json error:" + text + ":", var7);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }


    public static void writeJson(HttpServletResponse response, String json) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.print(json);
        } catch (IOException var7) {
            log.error("write json error:" + json + ":", var7);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    public static void writeFile(HttpServletResponse response, File file) throws Exception {
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(), "UTF-8"));
        response.setContentType("application/octet-stream;charset=UTF-8");
        //获取下载文件的输入流
        FileInputStream fis = new FileInputStream(file);
        //创建缓冲区
        int len = 0;
        byte[] bytes = new byte[1024];
        //创建输出流
        ServletOutputStream sot = response.getOutputStream();
        //写出文件
        while ((len = fis.read(bytes)) != -1) {
            sot.write(bytes, 0, len);
            sot.flush();
        }
        //关闭流
        sot.close();
        fis.close();
    }


}
